package com.ysd.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysd.common.exception.RRException;
import com.ysd.modules.app.dao.TopicDao;
import com.ysd.modules.sys.dao.*;
import com.ysd.modules.sys.entity.*;
import com.ysd.modules.sys.model.AutoTopicReq;
import com.ysd.modules.sys.model.StatusReq;
import com.ysd.modules.sys.service.PaperInfoService;
import com.ysd.modules.sys.service.TestPaperService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dapeng
 * @since 2021-07-19
 */
@Service
public class TestPaperServiceImpl extends ServiceImpl<TestPaperDao, TestPaper> implements TestPaperService {

    @Autowired
    private ChapterDao chapterDao;

    private PaperInfoService paperInfoService;
    @Resource
    private SysClassesDao sysClassesDao;
    @Resource
    private SysStudentDao sysStudentDao;
    @Resource
    private TopicSysDao topicSysDao;
    @Resource
    private PaperInfosDao paperInfosDao;

    @Override
    public IPage<TestPaper> listSearch(Map<String, Object> params) {
        QueryWrapper wrapper = new QueryWrapper();
        Integer page = Integer.parseInt(params.get("page").toString());
        Integer limit = Integer.parseInt(params.get("limit").toString());
        Page<TestPaper> currPage = new Page<>();
        currPage.setCurrent(page);
        currPage.setSize(limit);

        Object courseName = params.get("courseName");
        wrapper.like("course_name", courseName == null ? "" : courseName);

        Object title = params.get("title");
        wrapper.like("title", title == null ? "" : title);

        wrapper.ge("status", 0);
        IPage<TestPaper> iPage = this.baseMapper.selectPage(currPage, wrapper);
        return iPage;
    }

    @Override
    public TestPaper detailSearch(Integer id) {
        return this.getById(id);
    }

    @Override
    public void statusModify(StatusReq req) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.in("id", req.getIds());
        updateWrapper.set("status", req.getStatus());
        this.update(updateWrapper);
    }

    @Override
    public void autoTopic(List<AutoTopicReq> req) {
        Integer num = 0;
        List<PaperInfo> adds = new ArrayList<>();
        for (AutoTopicReq auto : req) {
            num += auto.getNum();
            Integer courseId = auto.getCourseId();

            if (auto.getChapterIds() == null || auto.getChapterIds().size() == 0) {
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.select("id");
                wrapper.eq("course_id", courseId);
                List<Chapter> list = chapterDao.selectList(wrapper);
                auto.setChapterIds(list.stream().map(Chapter::getId).collect(Collectors.toList()));
            }
        }
        adds = this.baseMapper.autoTopic(req);

        paperInfoService.saveBatch(adds);
    }

    /**
     * 发起考试
     *
     * @param testPaper
     * @param classId
     * @param chapters
     * @param type
     * @return
     */
    @Override
    @Transactional
    public int addPaper(TestPaper testPaper, Integer classId, Integer[] chapters, Integer type) {
        int len = baseMapper.insert(testPaper);
        if (len <= 0) {
            throw new RRException("试卷保存错误");
        }
        /**
         * 根据班级查询所有学生
         */
        SysClassesEntity classesEntity = sysClassesDao.selectById(classId);
        if (classesEntity == null) {
            throw new RRException("班级信息有误");
        }
        QueryWrapper<SysStudent> sq = new QueryWrapper<>();
        sq.eq("class_id", classId);
        List<SysStudent> sysStudentList = sysStudentDao.selectList(sq);
        if (sysStudentList == null || sysStudentList.size() <= 0) {
            throw new RRException("班级下没有学生");
        }
        for (int i = 0; i < sysStudentList.size(); i++) {
            SysStudent sysStudent = sysStudentList.get(i);
            Map<String, Object> params = new HashMap<>();
            params.put("stuId", sysStudent.getId());
            params.put("paperId", testPaper.getId());
            int len1 = baseMapper.insertStudentPaper(params);
            if (len1 <= 0) {
                throw new RRException("学生添加试卷失败");
            }
        }
        /**
         * 根据章节ID查询所有题目
         */
        if (chapters.length == 0) {
            throw new RRException("请选择课程章节信息");
        }
        /**
         * 保存试题信息
         */
        List<Topic> topics = topicSysDao.selectTopicListByRandom(testPaper.getTopicNum());
        if (topics == null || topics.size() <= 0) {
            throw new RRException("组题失败");
        }
        for (int i = 0; i < topics.size(); i++) {
            PaperInfo paperInfo = new PaperInfo();
            paperInfo.setPaperId(testPaper.getId());
            paperInfo.setTopicId(topics.get(i).getId());
            int len2 = paperInfosDao.insert(paperInfo);
            if (len2 <= 0) {
                throw new RRException("组题失败");
            }
        }
        return 1;
    }

    /**
     * select t.* from (
     * 	select top 1 t1.id as topicId from topic t1 where t1.chapter_id in (3)  order by newid()
     * 	union all
     * 	select top 1 t2.id as topicId from topic t2 where t2.chapter_id in (1)  order by newid()
     * ) t;
     */

}
